package com.rpframework.website.device.act.api;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonObject;
import com.rpframework.core.BaseAct;
import com.rpframework.module.common.domain.City;
import com.rpframework.module.common.pay.alipay.util.AlipayNotify;
import com.rpframework.module.common.service.CityService;
import com.rpframework.utils.NumberUtils;
import com.rpframework.website.device.domain.Balance;
import com.rpframework.website.device.domain.Estate;
import com.rpframework.website.device.domain.PayMent;
import com.rpframework.website.device.domain.Room;
import com.rpframework.website.device.domain.User;
import com.rpframework.website.device.exception.APICodeException;
import com.rpframework.website.device.service.BalanceService;
import com.rpframework.website.device.service.EstateService;
import com.rpframework.website.device.service.PayMentService;
import com.rpframework.website.device.service.RoomService;
import com.rpframework.website.device.service.UserService;
import com.rpframework.website.device.util.PayUtils;
@Controller
@RequestMapping("api/payment")
public class ApiPayMentAct extends BaseAct{
	@Resource PayMentService service;
	@Resource RoomService roomService;
	@Resource EstateService estateService;
	@Resource CityService cityService;
	@Resource UserService userService;
	@Resource BalanceService balanceService;
	public static Double val = 10d;//10积分=1RMB
	
  @RequestMapping(value="/detail",produces = "application/json; charset=utf-8")
	public @ResponseBody String Detail(
			@RequestParam Integer paymentId,//paymentId
			@RequestParam(value = "callback",required = false ) String callback,
			HttpSession session){
			JsonObject json = new JsonObject();
			/*  */
			User sessionuser=getSessionUser(session);
			if(sessionuser==null){
				throw new APICodeException(-4, "你还没登陆!");
			}
			User user = userService.select(sessionuser.getId());
			if(user == null)throw new APICodeException(-4, "你还没登陆!");
			Room r = roomService.select(sessionuser.getRoomId());
			if(r==null)throw new APICodeException(-9, "房间无效!");
			Estate e = estateService.select(r.getRelativeId());
			if(e==null)throw new APICodeException(-9, "小区无效!");
			City c = cityService.select(e.getCityCode());
			if(c==null)throw new APICodeException(-9, "城市无效!");
			StringBuffer sbf = new StringBuffer();
			sbf.append(c.getName()).append(e.getName()).append(r.getRoomZ()).append("幢").append(r.getRoomDy())
			.append("单元").append(r.getRoomNo()).append("室");	
			//gson.toJsonTree(li).getAsJsonObject();
			json.addProperty("room",sbf.toString());
			PayMent t = service.select(paymentId);
		
			json.addProperty("id",t.getId());
			json.addProperty("status",t.getStatus());
			json.addProperty("startTime", t.getStartTime().substring(0,7));
			json.addProperty("endTime", t.getEndTime().substring(0,7));
			json.addProperty("price", t.getPrice());
			
			json.addProperty("usePoint", user.getPoint());
			//如果积分除以val(10) 小于需付金额，则扣除全部积分，否则扣除金额*val(10)的积分
			Double d = t.getPrice()>user.getPoint()/val ? user.getPoint() : t.getPrice()*val;
			json.addProperty("deductPoint", d);//已扣积分
			json.addProperty("deductMoney", d/val);//抵扣金额等于 已扣积分/val(10)
			json.addProperty("realMoney", t.getPrice()-d/val > 0 ? t.getPrice() - d/val : 0);//实付金额
			//原价 一 抵扣金额  大于 0 就实付差额 ，否则就不用付款
			json.addProperty("balance", user.getBalance());
			json.add("remark", service.getJsonInfo());
			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
			return ""+json ;
	}
  @RequestMapping(value="/pay",produces = "application/json; charset=utf-8")
  public @ResponseBody String Pay(
		  @RequestParam Integer paymentId,//paymentId
		  @RequestParam Double realMoney,//实缴金额
		  @RequestParam Integer deductPoint,//扣除扣分
		  @RequestParam Integer payChannel,//支付方式 1支付 2微信  3余额
		  @RequestParam(value = "callback",required = false ) String callback,
		  HttpSession session) throws UnsupportedEncodingException{
	  JsonObject json = new JsonObject();
	  /*  */
	  User sessionuser=getSessionUser(session);
	  if(sessionuser==null){
		  throw new APICodeException(-4, "你还没登陆!");
	  }
	  User user = userService.select(sessionuser.getId());
	  if(user == null)throw new APICodeException(-4, "你还没登陆!");
	  PayMent t = service.select(paymentId);
	  if(t==null || t.getStatus() == 2)throw new APICodeException(-9, "缴费单无效或已缴费!");
	  if(realMoney == 0 || payChannel == 3){
		  if(user.getPoint()>=deductPoint){
			  user.setPoint(user.getPoint() - deductPoint);
		  }else{
			  throw new APICodeException(-9, "积分不足!");
		  }
		  //扣除用户的积分
		 if(payChannel == 3)//余额支付 且积分一定扣光了
		 user.setBalance(user.getBalance() - realMoney);
		 boolean f1 = userService.update(user);
		  //生成积分明细
		 boolean f2 =  balanceService.addRecord(Double.valueOf(deductPoint), "抵扣物业费",2 , user.getId());
		 //更改缴费单状态
		 t.setStatus(2);
		 t.setModifyTime(System.currentTimeMillis()/1000);
		 boolean f3 = service.update(t);
		 if(f1 && f2 && f3){
			 json.addProperty("code", 200);
		 }else{
			 json.addProperty("code", 500);
		 }
		 return (callback + "(" + json + ")");
	  }
	  //处理其它支付
	  if(payChannel == 1){//支付宝
		  //传入订单号，金额，subject和body需要的说明信息，回调处理方法
		  //积分没扣
		  return PayUtils.AliPay(t.getId(), t.getPrice(), "物业缴费",deductPoint.toString(), "/api/payment/test_alipay_succ", callback);
	  }
	  if(payChannel == 2){//微信
		  
	  }
	  return (callback + "(" + json + ")");
  }
  
  @SuppressWarnings({ "rawtypes", "unused" })
	@RequestMapping("/test_alipay_succ")
	public @ResponseBody String TestAliPaySucc(HttpServletRequest request) throws UnsupportedEncodingException{
		
		Logger logger = LoggerFactory.getLogger(getClass());
		logger.info("pay: 进入回调...." );
		String ret = "";
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		//订单号 100524+10位随机数
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		//交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
		logger.info("pay: 订单号："+out_trade_no+" \t 状态："+trade_status);
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
		
		String body = new String(request.getParameter("body").getBytes("ISO-8859-1"), "UTF-8");
		// 买家支付宝
		String buyerEmail = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"), "UTF-8");
		// 卖家支付宝
		String seller_email = new String(request.getParameter("seller_email").getBytes("ISO-8859-1"), "UTF-8");
		// 支付时间
		String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"), "UTF-8");
		// 交易状态
		String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		// 买家支付宝账户编号
		String buyer_id = new String(request.getParameter("buyer_id").getBytes("ISO-8859-1"), "UTF-8");
		
		if(AlipayNotify.verify(params)){//验证成功
			logger.info("pay: 验证succ=============");
			double total_fee = NumberUtils.parseDouble(request.getParameter("total_fee"));
			//////////////////////////////////////////////////////////////////////////////////////////
			if (trade_status.equals("TRADE_FINISHED")|| trade_status.equals("TRADE_SUCCESS")) {
				PayMent t = service.select(trade_no);
				t.setStatus(2);//已缴费
				boolean f1 = service.update(t);
				logger.info("pay: 订单状态更新：" + f1);
				/**
				 * 这里有支付记录的逻辑
				 * 记录表插入一条数据
				 */
			}
			//请在这里加上商户的业务逻辑程序代码
			ret = "success";	//请不要修改或删除
			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			logger.info("pay: error==========================");
			ret = "fail";
		}
		return ret;
	} 	
}
